
package mvcc

import (
	"go.etcd.io/etcd/server/v3/storage/backend"
	"go.etcd.io/etcd/server/v3/storage/schema"
)

func UnsafeReadFinishedCompact(tx backend.ReadTx) (finishedComact int64, found bool) {
	// 调用UnsafeRa口ge（）方法，在metaBucket中查询上次的压缩完成时的相关记录（Key为finishedCompactRev}
	_, finishedCompactBytes := tx.UnsafeRange(schema.Meta, schema.FinishedCompactKeyName, nil, 0)
	// 根据查询结果，恢复store.compactMainRev字段
	if len(finishedCompactBytes) != 0 {
		return bytesToRev(finishedCompactBytes[0]).main, true
	}
	return 0, false
}

func UnsafeReadScheduledCompact(tx backend.ReadTx) (scheduledComact int64, found bool) {
	// 调用UnsafeRange（）方法，在metaBucket中查询上次的压缩启动时的相关记录（Key为scheduledCompactRev)
	_, scheduledCompactBytes := tx.UnsafeRange(schema.Meta, schema.ScheduledCompactKeyName, nil, 0)
	// 根据查询结采，更新scheduledCompact交量
	if len(scheduledCompactBytes) != 0 {
		return bytesToRev(scheduledCompactBytes[0]).main, true
	}
	return 0, false
}

func SetScheduledCompact(tx backend.BatchTx, value int64) {
	tx.Lock()
	defer tx.Unlock()
	UnsafeSetScheduledCompact(tx, value)
}

func UnsafeSetScheduledCompact(tx backend.BatchTx, value int64) {
	rbytes := newRevBytes()
	revToBytes(revision{main: value}, rbytes)
	tx.UnsafePut(schema.Meta, schema.ScheduledCompactKeyName, rbytes)
}

func SetFinishedCompact(tx backend.BatchTx, value int64) {
	tx.Lock()
	defer tx.Unlock()
	UnsafeSetFinishedCompact(tx, value)
}

func UnsafeSetFinishedCompact(tx backend.BatchTx, value int64) {
	// 将compactMainRev封装成revision，并写入metaBucket中，其Key为“finishedCompactRev”
	rbytes := newRevBytes()
	revToBytes(revision{main: value}, rbytes)
	tx.UnsafePut(schema.Meta, schema.FinishedCompactKeyName, rbytes)
}
